import React,{useEffect,useState,useRef} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text, Image,
    TouchableWithoutFeedback, TextInput, TouchableOpacity,
} from 'react-native';
import Header from '../../widgets/Header';
import screen from '../../utils/screen';
import Constants from '../../utils/Constants';
import Images from '../../images/Images';
import SortDialog from '../../components/SortDialog';
import RefreshFlatList, {RefreshState} from '../../widgets/RefreshFlatList';
import {AppModal} from '../../widgets/modal';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import {getffly} from '../../utils/common';

const tabTitles = [Constants.team.direct,Constants.team.indirect,Constants.team.third_layer]
const sortTitles = [
    {
        title:Constants.team.registration_date,
        subTitle:Constants.team.sort_by_registration_date
    },{
        title:Constants.team.recharge_amount,
        subTitle:Constants.team.sort_by_recharge_amount
    },{
        title:Constants.team.team_members,
        subTitle:Constants.team.sort_by_team_members
    },{
        title:Constants.team.reward,
        subTitle:Constants.team.sort_by_referral_rewards
    },
]

const getLevelImage = (level)=>{
    if(level === 1) return Images.level1
    if(level === 2) return Images.level2
    if(level === 3) return Images.level3
    if(level === 4) return Images.level4
    if(level === 5) return Images.level5
    if(level === 6) return Images.level6

}

export default ({navigation})=>{


    const [sortIndex,setSortIndex] = useState(0)
    const [tabIndex,setTabIndex] = useState(0)
    const [refreshState,setRefreshState] = useState( RefreshState.Idle)
    const [data,setData] = useState(null)
    const sortDialog = useRef()
    useEffect(()=>{
        getData()
    },[sortIndex,tabIndex])

    const getData = ()=>{

        AppModal.showLoading();

        let param = {
            tier:1,
            sortBy:'registration'
        }
        if(tabIndex === 1){
            param.tier = 2
        } else if(tabIndex === 2){
            param.tier = 3
        }

        if(sortIndex === 0){
            param.sortBy = 'registration'
        }else if(sortIndex === 1){
            param.sortBy = 'recharge'
        }else if(sortIndex === 2){
            param.sortBy = 'members'
        }else if(sortIndex === 3){
            param.sortBy = 'rewards'
        }


        RequestUtil.get(Api.memberDetail,param).then(res=>{

            let data = res.data
            console.log('memberDetail',data)
            AppModal.hideTip()
            setData(data.list)
            if(data.list.length > 0){
                setRefreshState(RefreshState.Idle)
            }else{
                setRefreshState(RefreshState.EmptyData)
            }

        },error=>{
            AppModal.hideTip()
            if(error.code === -111){
                AppModal.showError(error.msg)
            }else{
                AppModal.showError(error.msg)
            }
            console.log('memberDetail error',error)
        })

    }

    const renderItem = ({item,index})=>{
        console.log('item',item)
        return (
            <View style={{paddingVertical:screen.PIXEL_20}}>
                <ShadowBoxView

                    shadowOption={{
                        radius:screen.PIXEL_40,
                        color:'#000',
                        x:0,
                        y:0,
                        border:5
                    }}
                >
                    <View style={{justifyContent:'space-between',backgroundColor: '#fff',
                        padding:screen.PIXEL_40,borderRadius:screen.PIXEL_40
                    }}>
                        <View style={{flexDirection: 'row'}}>
                            <Text style={{color:'#000',fontSize: 16,fontWeight: 'bold'}}>{item.nickName}</Text>
                            <Image source={getLevelImage(item.level.id)}
                                   resizeMode={'contain'}
                                   style={{width:screen.PIXEL_40,height:screen.PIXEL_40,marginHorizontal:screen.PIXEL_10}}
                            />
                            <Text style={{color:'#000',fontSize: 16}}>Lv.{item.level.name}</Text>

                        </View>
                        <Text style={{color:'#999',fontsize:13}}>{`Mobile：${item.mobile}`}</Text>
                        <Text style={{color:'#999',fontsize:13}}>{`${Constants.team.registered_on} ${item.signedup}`}</Text>
                        <View style={{flexDirection:'row',marginTop:screen.PIXEL_20}}>
                            <View style={{flex:1,alignItems:'center'}}>
                                <Text style={{fontSize:15,color:'#000'}}>{''}</Text>
                                <Text style={{fontSize:15,color:'#000'}}>{'order'}</Text>
                                <Text style={{fontSize:15,color:'#000'}}>{'recharge'}</Text>
                                <Text style={{fontSize:15,color:'#000'}}>{'commission'}</Text>
                            </View>

                            <View style={{flex:1,alignItems:'center'}}>
                                <Text style={{fontSize:15,color:'#000'}}>{"Today's"}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.order.today}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.recharge.today}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.commission.today}</Text>
                            </View>

                            <View style={{flex:1,alignItems:'center'}}>
                                <Text style={{fontSize:15,color:'#000'}}>{"Total"}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.order.total}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.recharge.total}</Text>
                                <Text style={{fontSize:15,color:'#FF7B14'}}>{item.commission.total}</Text>
                            </View>

                        </View>
                    </View>

                </ShadowBoxView>
            </View>
        )
    }

    let emptyComponent = (
        <View style={{ height:screen.PIXEL_400,justifyContent:'center', alignItems: 'center', }}>
            <Image
                source={ Images.empty}
                resizeMode={'contain'}
                style={{ width:screen.PIXEL_200, height: screen.PIXEL_200 }}
            />
            <Text style={{fontFamily:getffly("regular"), color: '#A6C4C3', fontSize: 14, marginTop: screen.PIXEL_30 }}>{'No record'}</Text>
        </View>
    )



    const renderTabBar = ()=>{

        return (
            <View style={styles.tabBar}>
                {
                    tabTitles.map((item,index)=>{
                        const isSelect = tabIndex === index
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.tabBarItem}
                                activeOpacity={1}
                                onPress={()=>{
                                    setTabIndex(index)
                                }}
                            >
                                <View style={isSelect ? styles.tabItemSelectBg  : {backgroundColor: '#fff'} }>
                                    <Text style={{fontSize:12,color:isSelect ? '#000' : '#BABABA'}}>{item}</Text>
                                </View>

                            </TouchableOpacity>
                        )
                    })
                }
                <TouchableOpacity
                    style={{width:screen.PIXEL_250,flexDirection: 'row',justifyContent:'center',alignItems:'center'}}
                    onPress={()=>{
                        sortDialog.current.show()
                    }}
                >
                    <Text style={{fontSize:12,color:'#377C74'}}>{sortTitles[sortIndex].title}</Text>
                    <Image source={Images.bottom}
                           resizeMode={'contain'}
                           style={{width:screen.PIXEL_30,height:screen.PIXEL_30,marginLeft:3}}/>

                </TouchableOpacity>

            </View>
        )
    }



    return (
        <View style={styles.container}>

            <Header title={Constants.team.team_members} navigation={navigation}/>
            {renderTabBar()}

            <RefreshFlatList
                contentContainerStyle={{
                    paddingVertical:screen.PIXEL_30,
                    paddingHorizontal:screen.PIXEL_40,
                }}
                refreshState={refreshState}

                renderItem={renderItem}
                data={data}
                footerEmptyDataComponent={emptyComponent}
                onHeaderRefresh={()=>{
                    getData()
                }}

            />


            <SortDialog ref={sortDialog}
                        data={sortTitles}
                        curIndex={sortIndex}
                        onSelect={(index)=>{
                            setSortIndex(index)
                        }}
            />

        </View>
    )
}
const tabItemHeight = screen.scaleSize(64)
const styles= StyleSheet.create({
    container:{
        flex:1,
        backgroundColor: '#fff'
    },
    content:{
        flex:1,
        paddingHorizontal:screen.PIXEL_40
    },tabBar:{
        height:screen.PIXEL_70,
        paddingHorizontal:screen.PIXEL_20,
        flexDirection:'row',
        alignItems:'center'
    },
    tabBarItem:{
        flex:1,
        justifyContent:'center',
        alignItems: 'center'
    },
    tabItemSelectBg:{
        width:screen.PIXEL_150,
        height:tabItemHeight,
        justifyContent:'center',
        alignItems: 'center',
        backgroundColor:'rgba(55,124,116,0.26)',
        borderTopLeftRadius:tabItemHeight/2,
        borderTopRightRadius: tabItemHeight/2,
        borderBottomLeftRadius:tabItemHeight/2

    }

})
